package com.hikeen.launcherx;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hikeen.launcherx.adapter.BottomAdapter;
import com.hikeen.launcherx.adapter.TestAdapter;
import com.hikeen.launcherx.bean.AppInfos;
import com.hikeen.launcherx.bean.AppInfoss;
import com.hikeen.launcherx.bean.PictureInfo;
import com.hikeen.launcherx.floatwindow.EventMessage;
import com.hikeen.launcherx.ui.MainActivity3;
import com.hikeen.launcherx.utils.AppUtils;
import com.hikeen.launcherx.utils.GsonUtils;
import com.hikeen.launcherx.utils.SPUtils;
import com.hikeen.launcherx.utils.ShowBigPhoto;
import com.hikeen.launcherx.utils.ShowBigPhotoActivity;
import com.hjq.toast.ToastUtils;
import com.hikeen.launcherx.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;

public class OneFramgent extends Fragment implements View.OnClickListener {
    private TextView text;
    private RecyclerView top_recycle;
    private RecyclerView bottom_recycle;
    private LinearLayoutManager linearLayoutManager;
    private List<AppInfos> newallApp = new ArrayList<>();
    private List<AppInfos> newallApp2 = new ArrayList<>();
    private TestAdapter testAdapter;
    private List<HashMap<String, Object>> maps;
    private LinearLayout clear_all1;
    private LinearLayout clear_all2;
    private String filePath;
    private BottomAdapter bottomAdapter;
    private List<String> imagePathFromSD;
    private LinearLayout ll_more;
    private LinearLayoutManager linearLayoutManager1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one_layout, container, false);
        initView(view);
        onHiddenChanged(false);
        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //相当于Fragment的onResume
            Log.e("onHiddenChanged", "onHiddenChanged: " + "one显示了");
            //  chushihua();
        } else {
            //相当于Fragment的onPause
            Log.e("onHiddenChanged", "onHiddenChanged: " + "one隐藏了");
        }
    }

    public void chushihua() {


        imagePathFromSD = getImagePathFromSD();

        ArrayList<AppInfos> appInfo = AppUtils.getAppInfo(getContext());

        String s = SPUtils.getString("savelist", "");
        Log.e("接收appinfo", "onMessageEvent: " + s);
        List<AppInfoss> appInfosses = GsonUtils.getPersons(s, AppInfoss.class);
        newallApp = new ArrayList<>();
        if (appInfosses != null && appInfosses.size() > 0) {
            for (int i = 0; i < appInfosses.size(); i++) {
                for (int j = 0; j < appInfo.size(); j++) {
                    if (appInfo.get(j).getAppName().equals(appInfosses.get(i).getAppName()) &&
                            appInfo.get(j).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                        newallApp.add(appInfo.get(j));
                    }
                }
            }
        }
        newallApp2 = new ArrayList<>();

        if (newallApp.size() > 6) {
            for (int i = 0; i < newallApp.size(); i++) {
                newallApp2.add(newallApp.get(i));
            }
        } else {
            int aa = 7 - newallApp.size();
            for (int i = 0; i < newallApp.size(); i++) {
                newallApp2.add(newallApp.get(i));
            }
            for (int i = 0; i < aa; i++) {
                newallApp2.add(new AppInfos());
            }
        }

        //倒序
        Collections.reverse(newallApp2);


        testAdapter = new TestAdapter(getContext(), newallApp2);
        top_recycle.setAdapter(testAdapter);

        top_recycle.smoothScrollToPosition(newallApp2.size() - 1);


        testAdapter.setOnItemClickListener(new TestAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, View v) {
                switch (v.getId()) {
                    case R.id.item_app_icon:
                        //这里通过包名来跳转
                        MainActivity3.isShowOne = true;
                        Intent mIntent = new Intent();
                        PackageManager packageManager = getActivity().getPackageManager();
                        AppInfos appInfo = newallApp2.get(position);
                        mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                        if (mIntent != null) {
                            startActivity(mIntent);
                        }
                        break;
                    case R.id.item_close:
                        new AlertDialog.Builder(getContext()).setTitle("确定清理当前应用？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定触发的事件
                                        newallApp2.remove(newallApp2.get(position));

                                        newallApp2.add(0, new AppInfos());
//                                            testAdapter.notifyDataSetChanged();

//                                            L.e("接收appinfo", "newallApp2: " + new Gson().toJson(newallApp2));
                                        List<AppInfoss> saveL = new ArrayList<>();

                                        for (int i = 0; i < newallApp2.size(); i++) {
                                            if (!TextUtils.isEmpty(newallApp2.get(i).getAppName()) && !TextUtils.isEmpty(newallApp2.get(i).getPackageName())) {
                                                AppInfoss appInfoss = new AppInfoss();
                                                appInfoss.setAppName(newallApp2.get(i).getAppName());
                                                appInfoss.setPackageName(newallApp2.get(i).getPackageName());
                                                saveL.add(appInfoss);
                                            }
                                        }
                                        Collections.reverse(saveL);
                                        String s = new Gson().toJson(saveL);
//                                            L.e("接收appinfo", "newallApp2  s :  " + s);
                                        SPUtils.putString("savelist", s);

                                        chushihua();

                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击取消触发的事件
                                    }
                                }).show();
                        break;
                }

            }


        });


        //下面list刷新


        imagePathFromSD = getImagePathFromSD();
        List<PictureInfo> infos = new ArrayList<>();
//        for (String str : imagePathFromSD) {
//            PictureInfo info = new PictureInfo();
//            info.picdz = str;
//            infos.add(info);
//        }


        for (int i = 0; i < imagePathFromSD.size(); i++) {
            PictureInfo info = new PictureInfo();
            info.picdz = imagePathFromSD.get(i);
            infos.add(info);
        }
        if (infos.size() < 7) {
            for (int i = 0; i < 7 - imagePathFromSD.size(); i++) {
                PictureInfo info = new PictureInfo();
                info.picdz = "";
                infos.add(info);
            }
        }


        //倒序
        Collections.reverse(infos);
        bottom_recycle.smoothScrollToPosition(infos.size() - 1);
        bottomAdapter = new BottomAdapter(getContext(), infos);

        bottomAdapter.setOnItemClickListener(new BottomAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, View v) {
                switch (v.getId()) {
                    case R.id.item_close:
                        new AlertDialog.Builder(getContext()).setTitle("确定删除当前文件？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    private List<PictureInfo> infoss;

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定触发的事件
                                        Log.e("--Method--11111", "deleteDirectory: " + infos.get(position).getPicdz());
                                        if (!TextUtils.isEmpty(infos.get(position).getPicdz())) {
                                            AppUtils.deleteSingleFile(infos.get(position).getPicdz());
                                            infos.remove(position);
                                        }


                                        infoss = new ArrayList<>();
                                        infoss.addAll(infos);

                                        bottom_recycle.smoothScrollToPosition(infoss.size() - 1);
//                                bottomAdapter = new BottomAdapter(getContext(), infoss);
//                                bottom_recycle.setAdapter(bottomAdapter);
//                                bottomAdapter.notifyDataSetChanged();
                                        bottomAdapter.setMlist(infoss);

                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击取消触发的事件
                                    }
                                }).show();
                        break;
                    case R.id.item_app_icon:
//                        ShowBigPhoto showBigPhoto = new ShowBigPhoto(getContext(), infos.get(position).getPicdz());
//                        showBigPhoto.showDetailPhoto();

                        MainActivity3.isShowOne = true;
                        Intent intent = new Intent(getActivity(), ShowBigPhotoActivity.class);
                        intent.putExtra("path", infos.get(position).getPicdz());
                        startActivity(intent);
                        break;
                }

            }
        });
        bottom_recycle.setAdapter(bottomAdapter);
    }


    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    private List<String> getImagePathFromSD() {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径   File.separator(/)
        filePath = Environment.getExternalStorageDirectory().toString() + File.separator
                + "MyPic/Part";
//                + "Pictures";
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        if (files != null) {
            // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                Log.e("name", "getImagePathFromSD: " + file.getPath());
                if (checkIsImageFile(file.getPath())) {
                    imagePathList.add(file.getPath());
                }
            }
        }
        Collections.sort(imagePathList, Collections.reverseOrder());

        // 返回得到的图片列表
        if (imagePathList.size() <= 10) {
            return imagePathList;
        } else {
            return imagePathList.subList(0, 10);
        }
    }


    /**
     * 检查扩展名，得到图片格式的文件
     *
     * @param fName 文件名
     * @return
     */
    @SuppressLint("DefaultLocale")
    private boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg") || FileEnd.equals("bmp")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    private void initView(View view) {

        TextView zjyy = (TextView) view.findViewById(R.id.tv_zjyy);
        TextView pmjt = (TextView) view.findViewById(R.id.tv_pmjt);

        zjyy.getPaint().setAntiAlias(true);
        pmjt.getPaint().setAntiAlias(true);

        ButterKnife.bind(getActivity());

        text = (TextView) view.findViewById(R.id.text);
        ll_more = (LinearLayout) view.findViewById(R.id.ll_more);
        top_recycle = view.findViewById(R.id.top_recycle);
        bottom_recycle = view.findViewById(R.id.bottom_recycle);
        clear_all1 = view.findViewById(R.id.clear_all1);
        clear_all2 = view.findViewById(R.id.clear_all2);
        clear_all1.setOnClickListener(this);
        clear_all2.setOnClickListener(this);
        ll_more.setOnClickListener(this);


        List<AppInfos> appInfo = AppUtils.getAppInfo(getContext());

        String s = SPUtils.getString("savelist", "");
        Log.e("接收appinfo", "onMessageEvent: " + s);
        List<AppInfoss> appInfosses = GsonUtils.getPersons(s, AppInfoss.class);
        newallApp = new ArrayList<>();
        if (appInfosses != null && appInfosses.size() > 0) {
            for (int i = 0; i < appInfosses.size(); i++) {
                for (int j = 0; j < appInfo.size(); j++) {
                    if (appInfo.get(j).getAppName().equals(appInfosses.get(i).getAppName()) &&
                            appInfo.get(j).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                        newallApp.add(appInfo.get(j));
                    }
                }
            }
        }

        newallApp2 = new ArrayList<>();
        if (newallApp.size() > 6) {
            for (int i = 0; i < newallApp.size(); i++) {
                newallApp2.add(newallApp.get(i));
            }
        } else {
            int aa = 7 - newallApp.size();
            for (int i = 0; i < newallApp.size(); i++) {
                newallApp2.add(newallApp.get(i));
            }
            for (int i = 0; i < aa; i++) {
                newallApp2.add(new AppInfos());
            }
        }

        Collections.reverse(newallApp2);


        linearLayoutManager1 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true);

        top_recycle.setLayoutManager(linearLayoutManager1);

        top_recycle.smoothScrollToPosition(newallApp2.size() - 1);


        testAdapter = new TestAdapter(getContext(), newallApp2);


        top_recycle.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
//                if (parent.getChildPosition(view) != (newallApp2.size() - 1)) {
//                    outRect.left = -132;
//                } else {
//                    outRect.left = 0;
//                }
            }
        });

        top_recycle.setAdapter(testAdapter);
        testAdapter.setOnItemClickListener(new TestAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, View v) {
                switch (v.getId()) {
                    case R.id.item_app_icon:
                        MainActivity3.isShowOne = true;
                        //这里通过包名来跳转
                        Intent mIntent = new Intent();
                        PackageManager packageManager = getActivity().getPackageManager();
                        AppInfos appInfo = newallApp2.get(position);
                        mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                        if (mIntent != null) {
                            startActivity(mIntent);
                        }
                        break;
                    case R.id.item_close:
                        new AlertDialog.Builder(getContext()).setTitle("确定清理当前应用？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定触发的事件
                                        newallApp2.remove(newallApp2.get(position));

                                        newallApp2.add(0, new AppInfos());
//                                            testAdapter.notifyDataSetChanged();

//                                            L.e("接收appinfo", "newallApp2: " + new Gson().toJson(newallApp2));
                                        List<AppInfoss> saveL = new ArrayList<>();

                                        for (int i = 0; i < newallApp2.size(); i++) {
                                            if (!TextUtils.isEmpty(newallApp2.get(i).getAppName()) && !TextUtils.isEmpty(newallApp2.get(i).getPackageName())) {
                                                AppInfoss appInfoss = new AppInfoss();
                                                appInfoss.setAppName(newallApp2.get(i).getAppName());
                                                appInfoss.setPackageName(newallApp2.get(i).getPackageName());
                                                saveL.add(appInfoss);
                                            }
                                        }
                                        Collections.reverse(saveL);
                                        String s = new Gson().toJson(saveL);
//                                            L.e("接收appinfo", "newallApp2  s :  " + s);
                                        SPUtils.putString("savelist", s);

                                        chushihua();

                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击取消触发的事件
                                    }
                                }).show();
                        break;
                }

            }


        });


        imagePathFromSD = getImagePathFromSD();
        List<PictureInfo> infos = new ArrayList<>();
//        for (String str : imagePathFromSD) {
//            PictureInfo info = new PictureInfo();
//            info.picdz = str;
//            infos.add(info);
//        }


        for (int i = 0; i < imagePathFromSD.size(); i++) {
            PictureInfo info = new PictureInfo();
            info.picdz = imagePathFromSD.get(i);
            infos.add(info);
        }
        if (infos.size() < 7) {
            for (int i = 0; i < 7 - imagePathFromSD.size(); i++) {
                PictureInfo info = new PictureInfo();
                info.picdz = "";
                infos.add(info);
            }
        }


        //倒序
        Collections.reverse(infos);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true);

        bottom_recycle.setLayoutManager(linearLayoutManager2);

        bottom_recycle.smoothScrollToPosition(infos.size() - 1);
        bottomAdapter = new BottomAdapter(getContext(), infos);

        bottom_recycle.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
//                if (parent.getChildPosition(view) != (infos.size() - 1)) {
//                    outRect.left = -132;
//                }
            }
        });
        bottomAdapter.setOnItemClickListener(new BottomAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, View v) {
                switch (v.getId()) {
                    case R.id.item_close:
                        new AlertDialog.Builder(getContext()).setTitle("确定删除当前文件？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    private List<PictureInfo> infoss;

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定触发的事件
                                        Log.e("--Method--11111", "deleteDirectory: " + infos.get(position).getPicdz());
                                        if (!TextUtils.isEmpty(infos.get(position).getPicdz())) {
                                            AppUtils.deleteSingleFile(infos.get(position).getPicdz());
                                            infos.remove(position);
                                        }


                                        infoss = new ArrayList<>();
                                        infoss.addAll(infos);

                                        bottom_recycle.smoothScrollToPosition(infoss.size() - 1);
//                                bottomAdapter = new BottomAdapter(getContext(), infoss);
//                                bottom_recycle.setAdapter(bottomAdapter);
//                                bottomAdapter.notifyDataSetChanged();
                                        bottomAdapter.setMlist(infoss);

                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击取消触发的事件
                                    }
                                }).show();
                        break;
                    case R.id.item_app_icon:
                        ShowBigPhoto showBigPhoto = new ShowBigPhoto(getContext(), infos.get(position).getPicdz());
                        showBigPhoto.showDetailPhoto();
                        break;
                }

            }
        });
        bottom_recycle.setAdapter(bottomAdapter);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_all1:
                if (newallApp.size() >= 1) {

                    new AlertDialog.Builder(getContext()).setTitle("确定清理当前所有应用？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //点击确定触发的事件
                                    newallApp.clear();
                                    newallApp2.removeAll(newallApp2);
                                    SPUtils.putString("savelist", "");
                                    testAdapter.notifyDataSetChanged();


                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //点击取消触发的事件
                                }
                            }).show();


                }


                break;
            case R.id.clear_all2:
                if (imagePathFromSD.size() >= 1) {
                    new AlertDialog.Builder(getContext()).setTitle("确定删除当前所有文件？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //点击确定触发的事件
                                    AppUtils.deleteDirectory(filePath);


                                    imagePathFromSD = getImagePathFromSD();
                                    List<PictureInfo> infos = new ArrayList<>();
                                    for (String str : imagePathFromSD) {
                                        PictureInfo info = new PictureInfo();
                                        info.picdz = str;
                                        infos.add(info);
                                    }
                                    //倒序
                                    Collections.reverse(infos);

                                    bottomAdapter = new BottomAdapter(getContext(), infos);
                                    bottom_recycle.setAdapter(bottomAdapter);
                                    bottomAdapter.notifyDataSetChanged();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //点击取消触发的事件
                                }
                            }).show();
                }

                break;
            case R.id.ll_more:
                fileOpen();
                break;

        }
    }


    private void fileOpen() {
        MainActivity3.isShowOne = true;
//        Intent intent = new Intent();
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+ "MyPic"+ File.separator+ "Part";
//        ComponentName wifiClassName = new ComponentName("com.hikeen.filemanager", "om.hikeen.filemanager.activities.MainActivity");
//        intent.setComponent(wifiClassName);
//        intent.putExtra("path", path);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);

        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPic" + File.separator + "Part";
        if (new File(path).exists()) {
            Intent intent = new Intent();
            ComponentName wifiClassName = new ComponentName("com.hikeen.filemanager", "com.hikeen.filemanager.activities.MainActivity");
            intent.setComponent(wifiClassName);
            intent.putExtra("path", path);
            Log.e("fileOpen", "path = " + path);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            ToastUtils.show("暂无屏幕截图！");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        // Do something
        if (event.getType() == 8) {
            if (event.getMessage().equals("addlist")) {
                chushihua();
                Log.e("初始化", "onMessageEvent: " + "添加初始化执行了");
            } else {
                chushihua();
                Log.e("初始化", "onMessageEvent: " + "卸载初始化执行了");
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
